import { Component, OnInit } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { MatSnackBar } from '@angular/material';
import { CookieService } from 'ng2-cookies';
import { HttpErrorResponse } from '@angular/common/http';

import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  username: string;
  accessToken: string;
  isRememb = false;
  isAutoLogin = false;

  constructor(
    public router: Router,
    public snackBar: MatSnackBar,
    public cookieService: CookieService,
    private authService: AuthService
  ) { }

  ngOnInit() {
    if (this.cookieService.get('isRememb') == 'true') {
      this.isRememb = true;
      this.username = this.cookieService.get('username');
    }
  }

  login(): void {
    this.authService
      .getUserByAccessToken(this.accessToken)
      .subscribe(
        user => {
          this.authService.login(this.accessToken);
          this.router.navigate(['']);
          this.snackBar.open("欢迎：" + user.name + "！", "", {
            duration: 1000
          });
        },
        (err: HttpErrorResponse) => this.handleError(err)
    )
  }

  handleError(err: HttpErrorResponse): void {
    if (err.error instanceof Error) {
      this.snackBar.open(err.error.message, "", {
        duration: 1000,
      });
    } else {
      this.snackBar.open(err.status + " " + err.statusText, "", {
        duration: 1000,
      });
    }
  }

  logout() {
    this.authService.logout();
    this.cookieService.delete('auth');
  }

}
